<template>
    <div class="main-container">
        <div class="form-box">
            <el-form v-loading="loading" :rules="rules" :model="dataForm" ref="dataForm" label-width="82px" class="form" >
                <span class="title">广告名称</span>
                <el-row :gutter="41">
                  <el-col :span="10">
                    <el-form-item label="广告名称" prop="advertName">
                        <el-popover placement="top-start" trigger="focus" content="请输入 1 到 20 个字符">
                            <el-input slot="reference" :maxlength="20" v-model="dataForm.advertName" placeholder="请输入广告名称"></el-input>
                        </el-popover>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- <span class="title">广告权重</span> -->
                
                <span class="title">广告图片信息</span>
                <el-row :gutter="41">
                  <el-col :span="10">
                    <el-form-item label="权重" prop="weight" :rules="rules.weight">
                      <el-input-number v-model="dataForm.weight" :min="1" :max="99999" style="width:100%"></el-input-number>
                      <i>权重值设置越大，优先轮播该广告图</i>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item label="备注" prop="remark">
                        <el-popover placement="top-start" trigger="focus" content="请输入 1 到 50 个字符的备注">
                            <el-input slot="reference" :maxlength="50" v-model="dataForm.remark" placeholder="请输入备注"></el-input>
                        </el-popover>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="41">
                  <el-col :span="10">
                    <div class="describe"><font color='red'>* </font>封面 <i>(图片大小750 * 240, 支持 JPG JPEG PNG GIF 格式，100K以内的图片！)</i></div>
                    <!-- 判断是否为查看还是编辑还是添加 -->
                    <div>
                        <el-form-item label-width="0">
                            <fileUpload @onSuccess="btnAdvImg" @remove="fileFileRemove" :file-list-show.sync='AdvImg' :file-list.sync="arrList" :imgSize='0.09765625'>
                                <div class="el-upload-new el-upload-picture-new">
                                <div class="up-container el-upload">
                                    <i class="el-icon-plus"></i>
                                </div>
                                </div>
                            </fileUpload>
                        </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <span class="title">广告链接与自定义内容</span>
                <el-row :gutter="41">
                  <el-col :span="21">
                    <el-radio class="radio" v-model="dataForm.showType" label="0">广告链接</el-radio>
                    <el-radio class="radio" v-model="dataForm.showType" label="1">自定义内容</el-radio>
                    <div class="box" v-if="dataForm.showType === '0'">
                        <el-form-item label-width="0" prop="link">
                            <el-popover placement="top-start" trigger="focus" content="请输入http://或https://前缀链接">
                                <el-input slot="reference" :maxlength="100" v-model="dataForm.link" placeholder="请输入链接" style="width:46%"></el-input>
                            </el-popover>
                        </el-form-item>
                    </div>
                    <div v-else>
                        <el-form-item>
                            <Tinymce :id="tinymceId" :height="260" ref="dataForm.content" v-model="dataForm.html"></Tinymce>
                        </el-form-item>
                    </div>
                  </el-col>
                </el-row>
                <span class="title">投放区域</span>
                <div v-if="roleType == 1">
                    <el-row :gutter="41" class="item">
                            <el-col :span="10">
                                <el-form-item label-width="61px" label="省份" prop="provinceId" :rules="rules.provinceId">
                                    <province v-model="dataForm.provinceId" @change="provinceChange"></province>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="41" class="item">
                            <el-col :span="10" v-if="agentTypeState=='2' || agentTypeState=='3'">
                                <el-form-item label-width="61px" label="城市" prop="cityId" :rules="rules.cityId">
                                    <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="41" class="item">
                            <el-col :span="10" v-if="agentTypeState=='3'">
                                <el-form-item label-width="61px" label="区县" prop="areaId" :rules="rules.areaId">
                                    <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <template  v-if="agentTypeState=='1'">
                            <el-row :gutter="41" class="item">
                                <el-col :span="10">
                                    <el-form-item label-width="61px" label="城市">
                                        <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="41" class="item">
                                <el-col :span="10">
                                    <el-form-item label-width="61px" label="区县">
                                        <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </template>
                        <template  v-if="agentTypeState=='2'">
                            <el-row :gutter="41" class="item">
                                <el-col :span="10">
                                    <el-form-item label-width="61px" label="区县">
                                        <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </template>
                </div>
                <div v-else>
                    <el-row :gutter="41">
                        <el-col :span="10">
                            <el-form-item label-width="53px" label="省份">
                            <province v-model="dataForm.provinceId"></province>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41">
                        <el-col :span="10">
                            <el-form-item  label-width="53px" label="城市">
                            <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41">
                        <el-col :span="10">
                            <el-form-item label-width="53px" label="区县">
                                <region v-model="dataForm.areaId" :city="dataForm.cityId" ></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <div class="man-bom"></div>
                <el-row :gutter="41" type="flex" justify="center">
                  <el-col :span="2"><el-button @click="cancel">取消</el-button></el-col>
                  <el-col :span="2">
                    <el-button v-if="advertId" @click="preservation('dataForm')" type="primary">保存</el-button>
                    <el-button v-else @click="addAdv('dataForm')" type="primary">新增</el-button>
                  </el-col>
                </el-row>
                <div class="man-bom"></div>
            </el-form>
        </div>
    </div>
</template>

<script>
import fileUpload from 'components/Upload/fileUpload';
import Tinymce from 'components/Tinymce';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import {
  getAdvertInfoById,
  updateAdvert,
  saveAdvert,
  listOrgRegionMapInfo
} from 'api/advApi';
import { mapGetters } from 'vuex';
export default {
    name: 'integralShop',
    components: { fileUpload, Tinymce, province, city, region },
    data() {
        return {
            AdvImg: true,
            dataForm: {
                advertPic: '',
                weight: '1',
                showType: '0',
                provinceId: '',
                cityId: '',
                areaId: '',
                advertName: '',
                remark: ''
            },
            onlineAgent: '',
            negativeAgent: '',
            tinymceId: 'tinymceId',
            arrList: [],
            loading: false,
            userTypeList: [],
            agentTypeState: 1,
      // 验证规则
            rules: {
                advertName: [
          { required: true, message: '请输入广告名称', trigger: 'blur' },
                    {
                        min: 1,
                        max: 20,
                        message: '长度为 1 到 20 个字符',
                        trigger: 'blur'
                    },
          { pattern: /^[^ ]+$/, message: '不能为空' }
                ],
                remark: [
          // { required: true, message: '请输入备注', trigger: 'blur' },
                    {
                        min: 1,
                        max: 50,
                        message: '长度为 1 到 50 个字符',
                        trigger: 'blur'
                    },
          { pattern: /^[^ ]+$/, message: '不能为空' }
                ],
                link: [
          // { required: true, message: '请输入url', trigger: 'blur' }
                    {
                        pattern: /^(https?):\/\/\w*\.\w*/,
                        message:
              "请填完整的广告链接，广告链接需以'http://'或者'https://'开头"
                    }
                ],
                weight: {
                    required: true,
                    type: 'number',
                    message: '请输入权重',
                    trigger: 'blur'
                },
                provinceId: [
          { required: true, message: '请选择省份', trigger: 'change' }
                ],
                cityId: [{ required: true, message: '请选择城市', trigger: 'change' }],
                areaId: [{ required: true, message: '请选择区县', trigger: 'change' }]
            }
        };
    },
    props: {
        advertId: {
            type: String,
            required: false
        },
        advType: {
            type: String,
            required: false
        }
    },
    created() {
        this.getAdvFoId();
        this.getAgentTypes();
    },
    computed: {
    // roleType 1 自定义角色  2 管理员  3 运营专用（其实与2相同，区分开来）
        ...mapGetters(['roleType'])
    },
    methods: {
    // 判断省市区代
        getAgentTypes() {
      // 省代理就是[1]，市代[2],区代[3],如果既是省代又是市代就是[1,2],如果既是省代又是市代又是区代就是[1,2,3]
            listOrgRegionMapInfo().then(response => {
                this.userTypeList = response.data.content;
            });
        },
        provinceChange(val) {
            let count = 0;
            this.userTypeList.some(item => {
                if (item.fProvinceId == val) {
                    if (count == 0) {
                        this.agentTypeState = item.fAgentType;
                    } else {
                        if (item.fAgentType == '1') {
                            this.agentTypeState = '1';
                        } else if (item.fAgentType == '2' && this.agentTypeState != '1') {
                            this.agentTypeState = '2';
                        } else if (
              item.fAgentType == '3' &&
              this.agentTypeState != '1' &&
              this.agentTypeState != '2'
            ) {
                            this.agentTypeState = '3';
                        }
                    }
                    count = count + 1;
                }
            });
        },
    // 查看广告
        getAdvFoId() {
            if (this.advertId) {
                this.loading = true;
                getAdvertInfoById(this.advertId)
          .then(data => {
              this.loading = false;
              this.dataForm = data.data.content;
            // 单个图片
              if (data.data.content.advertPic !== '') {
                  this.arrList.push({ name: '', url: data.data.content.advertPic });
              }
          })
          .catch(Error => {
              this.loading = false;
          });
            }
        },
    // 取消
        cancel() {
            this.$router.go(-1);
        },
    // 编辑保存
        preservation(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.dataForm.advertPic === '') {
                        this.$message('请上传图片(750 * 240)');
                        return false;
                    }
                    if (this.dataForm.showType === '1') {
                        if (
              window.tinymce
                .get('tinymceId')
                .getContent({ format: 'text' })
                .trim().length > 6000
            ) {
                            this.$message.error('自定义内容字数过多');
                            return false;
                        }
                    }
                    this.$confirm('确认编辑?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    })
            .then(() => {
                this.loading = true;
                updateAdvert(
                this.param(this.dataForm.advertName),
                this.param(this.advType),
                this.param(this.dataForm.remark),
                this.param(this.dataForm.appType),
                this.param(this.dataForm.advertPic),
                this.param(this.dataForm.iosOnePic),
                this.param(this.dataForm.iosTwoPic),
                this.param(this.dataForm.iosThreePic),
                this.param(this.dataForm.androidPic),
                this.param(this.dataForm.showTime) + '',
                this.param(this.dataForm.weight),
                this.param(this.dataForm.showType),
                this.param(this.dataForm.link),
                this.param(this.dataForm.html),
                this.param(this.dataForm.provinceId),
                this.param(this.dataForm.cityId),
                this.param(this.dataForm.areaId),
                this.param(this.advertId)
              )
                .then(data => {
                    this.loading = false;
                    this.$store.dispatch('UpdateCache', true);
                    this.$router.push({ path: '/operation' });
                    this.$message({
                        message: '编辑成功！',
                        type: 'success'
                    });
                })
                .catch(Error => {
                    this.loading = false;
                });
            })
            .catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
          // }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        btnAdvImg(obj) {
      // console.log(obj);
            this.dataForm.advertPic = `${obj.imgUrl}?imageView2/2/w/750/h/240`;
        },
        fileFileRemove(file) {
            this.dataForm.advertPic = '';
        },
    // 新增广告

        addAdv(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.dataForm.advertPic === '') {
                        this.$message('请上传图片(750 * 240)');
                        return false;
                    }
                    if (this.dataForm.showType === '1') {
                        if (
              window.tinymce
                .get('tinymceId')
                .getContent({ format: 'text' })
                .trim().length > 6000
            ) {
                            this.$message.error('自定义内容字数过多');
                            return false;
                        }
                    }
          // 判断省市区是否只有单个

                    this.$confirm('确认提交?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    })
            .then(() => {
                this.loading = true;
                saveAdvert(
                this.param(this.dataForm.advertName),
                this.param(this.advType),
                this.param(this.dataForm.remark),
                this.param(this.dataForm.appType),
                this.param(this.dataForm.advertPic),
                this.param(this.dataForm.iosOnePic),
                this.param(this.dataForm.iosTwoPic),
                this.param(this.dataForm.iosThreePic),
                this.param(this.dataForm.androidPic),
                this.param(this.dataForm.showTime),
                this.param(this.dataForm.weight) + '',
                this.param(this.dataForm.showType),
                this.param(this.dataForm.link),
                this.param(this.dataForm.html),
                this.param(this.dataForm.provinceId),
                this.param(this.dataForm.cityId),
                this.param(this.dataForm.areaId)
              )
                .then(data => {
                    this.loading = false;
                    this.$store.dispatch('UpdateCache', true);
                    this.$router.push({ path: '/operation' });
                    this.$message({
                        message: '添加成功！',
                        type: 'success'
                    });
                })
                .catch(Error => {
                    this.loading = false;
                });
            })
            .catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    // 判断参数
        param(val) {
            return !val ? '' : val;
        }
    }
};
</script>

<style lang="scss" scoped>
.man-bom {
  margin: 20px 0;
}
.box {
  margin: 20px 0;
}
.title {
  position: relative;
  font-size: 14px;
  color: rgb(106, 85, 72);
  padding-left: 14px;
  margin: 30px 0;
  display: block;
  &::after {
    position: absolute;
    content: "";
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: 0;
    top: 3px;
  }
}
.describe {
  font-size: 14px;
  color: #666;
  margin: 20px 0;
}
i {
  font-style: normal;
  color: #999;
}
</style>